package com.luzi.pro;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * 解析日志启动类
 */
public class StartLogExtend {
    private static List<LogItem> dataList = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        String logFilePath = "D:\\bak\\璐子的\\lulu\\mylog\\src\\main\\resources\\logFile.log";
        System.out.println("读取的日志文件路径:" + logFilePath);
        readLog(logFilePath);

        String excelPath = "D:\\bak\\璐子的\\lulu\\mylog\\src\\main\\resources\\log.xlsx";
        writeExcel(excelPath);
        System.out.println("生成的Excel路径:" + excelPath);
    }

    private static void readLog(String logFilePath) throws Exception {
        BufferedReader reader = new BufferedReader(new FileReader(logFilePath));
        String lineContent;
        List<String> lines = new ArrayList<>();
        int index = 0;
        boolean isFirst = true;
        while ((lineContent = reader.readLine()) != null) {
            index++;
            lines.add(lineContent);
            // 判断区块起始行,线
            if (lineContent.trim().startsWith("---------------------") && lineContent.trim().replace("-", "").length() == 0) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    readBlock(index, lines);
                    lines.clear();
                }
            }
        }
        if (lines.size() > 0) {
            readBlock(index, lines);
        }
    }

    /**
     * 读取分析单个block中的数据
     */
    private static void readBlock(int index, List<String> lines) throws Exception {
        LogItem logItem = new LogItem();
        for (int i = 0; i < lines.size(); i++) {
            String str = lines.get(i);
            logItem.setIndex(String.valueOf(index));
            if (logItem.getId() == null && str.trim().startsWith("ID:")) {
                logItem.setId(str.trim().substring("ID:".length()));
            } else if (logItem.getAddress() == null && str.trim().startsWith("Address:")) {
                logItem.setAddress(str.trim().substring("Address:".length()));
            } else if (logItem.getMethod() == null && str.trim().startsWith("Http-Method:")) {
                logItem.setMethod(str.trim().substring("Http-Method:".length()));
            } else if (logItem.getUserId() == null && str.trim().startsWith("Headers:")) {
                int userAt = str.indexOf("PCY_TEST_USERID=");
                // 在此行找到了
                if (userAt > -1) {
                    setUserId(str, logItem, userAt);
                } else { // 在此行没有找到,则继续往下找，直到碰到下一个标签
                    for (int j = i + 1; j < lines.size(); j++) {
                        String text = lines.get(j);
                        if (text.trim().startsWith("Payload:")) {
                            break;
                        }
                        userAt = text.indexOf("PCY_TEST_USERID=");
                        if (userAt > -1) {
                            setUserId(text, logItem, userAt);
                        }
                    }
                }
            } else if (logItem.getNsX() == null && str.trim().startsWith("Payload:")) {
                String keyNs = getKeyNS(str);
                // 在此行找到了
                if (keyNs != null) {
                    setNsX(str, logItem, keyNs);
                } else {// 在此行没有找到,则继续往下找知道结束
                    for (int j = i + 1; j < lines.size(); j++) {
                        String text = lines.get(j);
                        keyNs = getKeyNS(text);
                        if (keyNs != null) {
                            setNsX(text, logItem, keyNs);
                        }
                    }
                }
            } else if (logItem.getTime() == null && (str.trim().startsWith("2020-") || str.trim().startsWith("2019-"))) {
                // 时间字符串后的第一个空格
                int timeEnd = str.indexOf(" ", 12);
                if (timeEnd < 0) {
                    timeEnd = "2020-05-29 08:59:44.216".length() + 1;
                }
                logItem.setTime(str.substring(0, timeEnd));
            }
        }
        dataList.add(logItem);
    }

    private static void setUserId(String str, LogItem logItem, int userAt) {
        int end = str.indexOf("}", userAt);
        logItem.setUserId(str.substring(userAt + "PCY_TEST_USERID=".length() + 1, end));
    }

    private static void setNsX(String str, LogItem logItem, String keyNs) {
        int nsAt = str.indexOf(keyNs);
        int end = str.indexOf(">", nsAt);
        logItem.setNsX(str.substring(nsAt + keyNs.length() + 1, end));
    }

    private static String getKeyNS(String str) {
        Pattern compile = compile("(<ns)[0-9]+(:)");
        Matcher m = compile.matcher(str);
        if (m.find()) {
            return m.group();
        }
        return null;
    }

    private static void writeExcel(String excelPath) throws Exception {
        ExcelUtil<LogItem> excelExportUtil = new ExcelUtil<>();
        List<ExcelUtil.CellMap> cellMapList = new ArrayList<>();
        String[] titlesArray = {"index", "ID", "Address", "Http-Method", "PCY_TEST_USERID", "nsX", "TIME"};
        String[] varsArray = {"index", "id", "address", "method", "userId", "nsX", "time"};
        List<String> titles = new ArrayList<>();
        List<String> vars = new ArrayList<>();
        Collections.addAll(titles, titlesArray);
        Collections.addAll(vars, varsArray);
        for (int i = 0; i < titles.size(); i++) {
            cellMapList.add(new ExcelUtil.CellMap(titles.get(i), vars.get(i)));
        }
        excelExportUtil.exportSXSSFExcel("log", cellMapList, dataList, dataList.size(), excelPath);
    }

}
